package com.xybian.filter;

import com.xybian.entity.SysUser;
import com.xybian.util.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.naming.AuthenticationException;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil tokenUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) {
        // 获取 token
        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)){

            filterChain.doFilter(httpServletRequest,httpServletResponse);

            return;
        }
        // 解析token，获取 userId

        Claims claims = tokenUtil.getClaimsFromToken(token);

        String userId = claims.get("userId").toString();

        //从redis中获取User
        Object o = redisTemplate.opsForValue().get("user-" + userId);

        if (ObjectUtils.isEmpty(o)){
            throw new AuthenticationException("没有用户信息");
        }

        SysUser user = (SysUser)o;

        //用户权限信息
        List<SimpleGrantedAuthority> authorityList = user.getPermissions().stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        //将User 封装到 securityContextHolder。
        //封装到securityContextHolder以后，其他过滤器就不会在拦截
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null,authorityList);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
